package com.csdj.common.utils;


import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 对称加密
 * Created by cloud on 2017/10/10.
 */
public class EncrptyUtil {

    private static final String KEY = "KPNBCOIN19930314";

    public static String getMd5(String str){
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }


    public static String getSHA256Str(String str){
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }

    public static byte[] getSha256(byte[] input){
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(input);
            return messageDigest.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }




    public static String aesDecrypt(String src){
        return aesDecrypt(src,KEY);
    }

    /**
     * AES解密
     * @param sSrc 密文
     * @param sKey 密码
     * @return 明文
     * @throws Exception
     */
    public static String aesDecrypt(String sSrc, String sKey) {
        try {
            // 判断Key是否正确
            if (sKey == null || sSrc == null || "".equals(sSrc)) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = hex2byte(sSrc);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static String aesEncrypt(String src){
        return aesEncrypt(src,KEY);
    }

    /**
     * AES加密
     * @param sSrc 需要加密的原文
     * @param sKey 加密密钥钥匙
     * @return 密文
     * @throws Exception
     */
    public static String aesEncrypt(String sSrc, String sKey) {
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            System.out.print("Key长度不是16位");
            return null;
        }
        try {
            byte[] raw = sKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");// 根据给定的字符数组来构造一个密钥
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes());
            return byte2Hex(encrypted).toLowerCase();
        } catch (Exception e) {
            return null;
        }
    }

    public  static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i=0;i<bytes.length;i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length()==1){
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    public static byte[] hex2byte(String strhex) {
        if (StringUtils.isEmpty(strhex)) {
            return null;
        }
        int length = strhex.length();
        if (length % 2 != 0) {
            return null;
        }
        byte[] b = new byte[length / 2];
        for (int i = 0; i != length / 2; i++) {
            b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);
        }
        return b;
    }

    public static void main(String[] args) {
        //加密
        String en =aesEncrypt("123456");
        //打印密文
        System.out.println(en);
        //解密
        final String pass = aesDecrypt(en);
        //打印明文
        System.out.println(pass);
    }
}
